package monolithicapp

import (
	"context"
	"fmt"
	"log/slog"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type LogLevel int

const (
	// Silent silent log level
	Silent = iota + 1
	// Error error log level
	Error
	// Warn warn log level
	Warn
	// Info info log level
	Info
)

type MySQLClient struct {
	config   *MySQLConfig
	Conn     *gorm.DB
	callback func(conn *gorm.DB) // 初始化函数，用于在启动时执行一些操作，如创建表、插入数据等。可以根据需要自定义，也可以不设置。
}

func NewMySQLClient(config *MySQLConfig, callback func(conn *gorm.DB)) *MySQLClient {
	return &MySQLClient{config: config, callback: callback}
}

func (d *MySQLClient) Start(level LogLevel) error {
	if d.config == nil {
		slog.Error("db config is nil... ")
		return fmt.Errorf("db config is nil")
	}

	if d.config.User == "" || d.config.Password == "" || d.config.Host == "" || d.config.DBName == "" {
		slog.Error("db config is invalid... ")
		return fmt.Errorf("db config is invalid")
	}

	slog.Info("db config is valid... ", "host", d.config.Host, "port", d.config.Port, "user", d.config.User, "dbname", d.config.DBName)

	uri := fmt.Sprintf("%s:%s@(%s)/%s", d.config.User, d.config.Password, d.config.Host, d.config.DBName)
	var err error
	dns := fmt.Sprintf("%s?charset=utf8mb4&parseTime=True&loc=Local", uri)
	d.Conn, err = gorm.Open(mysql.Open(dns), &gorm.Config{
		PrepareStmt:                              false,
		Logger:                                   logger.Default.LogMode(logger.LogLevel(level)),
		CreateBatchSize:                          100, // 批量插入时 每次数据量
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		slog.Error("db connect failed... ", "error", err)
		return err
	}
	sqlDB, err := d.Conn.DB()
	if err != nil {
		slog.Error("db connect failed... ", "error", err)
		return err
	}
	// SetMaxIdleConns 设置空闲连接池中连接的最大数量
	sqlDB.SetMaxIdleConns(5)
	// SetMaxOpenConns 设置打开数据库连接的最大数量。
	sqlDB.SetMaxOpenConns(10)
	// SetConnMaxLifetime 设置了连接可复用的最大时间。
	sqlDB.SetConnMaxLifetime(time.Hour)

	d.callback(d.Conn)

	slog.Info("db connect success...")
	return nil
}

func (d *MySQLClient) Stop(ctx context.Context) error {
	sqlDB, err := d.Conn.DB()
	if err != nil {
		slog.Error("db close failed... ", "error", err)
		return err
	}
	return sqlDB.Close()
}
